﻿using System;
using System.Collections.Generic;
using System.Text;
using Pixysoft.Framework.Reflection;
using Pixysoft.Weblications.Sango.Dao;
using Pixysoft.Weblications.Sango.Protocol.player;
using Pixysoft.Weblications.Sango.Protocol.officer;
using Pixysoft.Weblications.Sango.Protocol;

namespace Pixysoft.Weblications.Sango.Command.player
{
    partial class SangoPlayerHandler
    {
        public player_recuit player_recuit()
        {
            string userCode = SangoManager.Authentication();

            player_recuit response = ReflectionManager.CreatePojo<player_recuit>();
            response.Succeed = false;

            //获取所有武将 计算征兵数目

            List<Entities.Usr_Officer> officers = OfficerDao.getUserInjobOfficers(userCode);
            Entities.Usr_Profile profile = UsrProfileDao.getUsrProfile(userCode);

            long soldiervalue = 0;
            foreach (Entities.Usr_Officer officer in officers)
            {
                soldiervalue += (officer.Hpbasevalue + officer.Hpaddvalue - officer.Currenthpvalue);
            }
            soldiervalue += profile.Maxsoldiervalue - profile.Soldiervalue;

            long recuitvalue = soldiervalue > profile.Resourcevalue ? profile.Resourcevalue : soldiervalue;

            if (!UsrProfileDao.tryDecreaseResourceValue(profile, recuitvalue))
            {
                response.Message = "粮草不足";
                return response;
            }

            IEntityNoebeTransaction command = SettingHelper.EntityTransaction;

            command.Begin(delegate()
            {
                //补充兵力

                foreach (Entities.Usr_Officer officer in officers)
                {
                    long needRecuitValue = officer.Hpaddvalue + officer.Hpbasevalue - officer.Currenthpvalue;

                    long decreaseRecuitValue = recuitvalue < needRecuitValue ? recuitvalue : needRecuitValue;

                    officer.Currenthpvalue += decreaseRecuitValue;

                    recuitvalue -= decreaseRecuitValue;

                    command.Update(officer);

                    if (recuitvalue <= 0)
                        break;
                }

                //补充储备

                if (recuitvalue > 0)
                {
                    profile.Soldiervalue += recuitvalue;

                    command.Update(profile);
                }

                command.Commit();
            });

            response.Succeed = true;
            response.userofficers = OfficerFacade.ToOfficers(OfficerDao.getUserOfficers(userCode));
            response.profile = UsrProfileFacade.ToProfile(profile);
            return response;
        }
    }

    public interface player_recuit : ISangoResponse
    {
        player_profile profile { get;set;}

        List<player_officer> userofficers { get;set;}
    }
}
